package net.rlair.sbdemo.service;

import net.rlair.sbdemo.dao.mybatis.bootmapper.UserMapper;
import net.rlair.sbdemo.entity.User;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by zyy on 2019/3/22.
 */
@Service
public class TxRequiresNewZhaoyuyang implements ApplicationContextAware{

    private ApplicationContext applicationContext;

    @Resource
    private UserMapper userMapper;

    @Override
    public void setApplicationContext(ApplicationContext var1) throws BeansException{
        this.applicationContext = var1;
    }

    @Transactional(isolation= Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
    public int batchAddUsers(){
        int count = 0;
        TxRequiresNewZhaoyuyang userService = applicationContext.getBean(TxRequiresNewZhaoyuyang.class);
        final List<User> users = new ArrayList();
        users.add(userService.mockUserData(10000));
        users.add(userService.mockUserData(10001));
        users.add(userService.mockUserData(10002));
        for (User user : users) {
            try {
                count +=userService.addUser(user);
            }catch (final Exception e){
                e.printStackTrace();
            }
        }
        count += userMapper.addUser(mockUserData(10003));
        return count;
    }

    @Transactional(isolation= Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRES_NEW)
    public int addUser(final User user){
        int count = userMapper.addUser(user);
        if (user.getId() == 10001){ //强制出错
            throw new RuntimeException();
        }
        return count;
    }

    public User mockUserData(int id) {
        final User user = new User();
        user.setId(id);
        user.setCreated(new Date());
        user.setName("name" + id);
        user.setPassword("password " + id);
        user.setUpdated(new Date());
        return user;
    }
}
